package com.aiden.app.common.widget.glide

import android.content.Context
import com.bumptech.glide.Glide

import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import com.aiden.app.common.util.LogUtils
import java.io.File
import java.io.InputStream

@GlideModule
class MyGlideModule : AppGlideModule() {
    private val TAG = MyGlideModule::class.java.simpleName
    private val M = 1024 * 1024L
    private val MAX_DISK_CACHE_SIZE = 256 * M

    companion object {
        fun clearMemoryCache(context: Context) {
            GlideApp.get(context).clearMemory()
        }
    }

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        val cachedDirName = "glide"
        builder.setDiskCache(ExternalPreferredCacheDiskCacheFactory(context, cachedDirName, MAX_DISK_CACHE_SIZE))
        LogUtils.i(TAG, "NIMGlideModule apply options, disk cached path=" + context.externalCacheDir + File.separator + cachedDirName)
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory())
    }
}
